/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： UserController.java
 * Date：18-11-6 下午3:11
 * Author: guomw
 */

package com.guomw.report.web.controller;

import com.guomw.report.common.config.Constant;
import com.guomw.report.common.enums.AppCode;
import com.guomw.report.common.utils.ApiResult;
import com.guomw.report.service.entity.Report;
import com.guomw.report.service.entity.UserGeneTesting;
import com.guomw.report.service.models.ReportView;
import com.guomw.report.service.models.Searcher;
import com.guomw.report.service.repository.ReportRepository;
import com.guomw.report.service.repository.UserGeneTestingRepository;
import com.guomw.report.service.service.ChainReportService;
import com.guomw.report.service.service.ConfigService;
import com.guomw.report.service.service.UserGeneTestingService;
import com.guomw.report.service.service.upload.StaticResourceService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * @author guomw
 * @date 2018/11/6
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserGeneTestingService userGeneTestingService;

    @Autowired
    private StaticResourceService resourceService;

    @Autowired
    private ChainReportService chainReportService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private UserGeneTestingRepository userGeneTestingRepository;

    @Autowired
    private ReportRepository reportRepository;

    /**
     * @return
     */
    @RequestMapping("/list")
    public String menusPage() {
        return "user/list";
    }


    /**
     * 获取用户基因测试数据
     *
     * @param keyword
     * @param status
     * @param barCode
     * @param pageIndex
     * @return
     */
    @RequestMapping(value = "/ajax/genetesting", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getGeneTesting(
            @RequestParam(required = false, defaultValue = "") String keyword,
            @RequestParam(required = false, defaultValue = "-1") Integer status,
            @RequestParam(required = false, defaultValue = "") String barCode,
            @RequestParam(required = false, defaultValue = "1") Integer pageIndex) {
        Searcher searcher = new Searcher();
        searcher.setKeyword(keyword);
        searcher.setPageIndex(pageIndex);
        searcher.setStatus(status);
        searcher.setBarCode(barCode);
        return ApiResult.resultWith(AppCode.SUCCESS, userGeneTestingService.searchList(searcher));
    }


//    @RequestMapping(value = "/uploadReportFile/{folder}")
//    @ResponseBody
//    public ApiResult uploadReportFile(@PathVariable("folder") String folder, HttpServletRequest req, HttpServletResponse resp) throws IOException, FileUploadException {
//        req.setCharacterEncoding("UTf-8");
//        //获取tomcat下的up目录的路径
//        String path = configService.getReportFileFolder() + "/" + folder;
//        //临时文件目录
//        String tmpPath = configService.getReportFileFolder() + "/temp";
//
//        //检查我们是否有文件上传请求
////        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
//        //1,声明DiskFileItemFactory工厂类，用于在指定磁盘上设置一个临时目录
//        DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tmpPath));
//        //2,声明ServletFileUpload，接收上边的临时文件。也可以默认值
//        ServletFileUpload up = new ServletFileUpload(disk);
//
//        List<FileView> views = new ArrayList<>();
//        //3,解析request
//        List<FileItem> list = up.parseRequest(req);
//        for (FileItem file : list) {
//            //如果就一个文件，
//            //获取文件名：
//            String fileName = file.getName();
//            //获取文件的类型：
//            String fileType = file.getContentType();
//            //获取文件的字节码：
//            InputStream in = file.getInputStream();
//            //文件大小
//            int size = file.getInputStream().available();
//            //声明输出字节流
//            OutputStream out = new FileOutputStream(path + "/" + fileName);
//            //文件copy
//            byte[] b = new byte[1024];
//            int len = 0;
//            while ((len = in.read(b)) != -1) {
//                out.write(b, 0, len);
//            }
//            out.flush();
//            out.close();
//
//            //删除上传生成的临时文件
//            file.delete();
//
////                pw.println("文件名：" + fileName);
////                pw.println("文件类型：" + fileType);
////                pw.println("<br/>文件大小（byte）：" + size);
//            FileView view = new FileView();
//            view.setName(fileName);
//            view.setSize(size);
//            views.add(view);
//        }
//
//        return ApiResult.resultWith(AppCode.SUCCESS, views);
//    }


    @RequestMapping("/uploads")
    public String uploads() {
        return "test/uploads";
    }

    /**
     * 生成文件
     *
     * @param file
     * @param folder
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFile/{folder}", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult uploadFile(@RequestParam(value = "file", required = false) MultipartFile file, @PathVariable("folder") String folder) throws IOException {

        File f = new File(configService.getReportFileFolder() + "/" + folder + "/" + file.getOriginalFilename());
        FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        return ApiResult.resultWith(AppCode.SUCCESS);
    }


    /**
     * 生成报告
     *
     * @param code
     * @param model
     * @return
     */
    @RequestMapping("/uploadReport/{code}")
    public String uploadReport(@PathVariable("code") String code, Model model) {
        model.addAttribute("code", code);
        model.addAttribute("test", userGeneTestingRepository.findOne(code));
        return "user/uploadreport";
    }


    @RequestMapping(value = "/findCheckFiles")
    @ResponseBody
    public ApiResult findCheckFiles(String code) {

        try {
            return ApiResult.resultWith(AppCode.SUCCESS, chainReportService.findFiles(configService.getReportFileFolder() + "/" + Constant.CHECKED, code));
        } catch (Exception e) {
            return ApiResult.resultWith(AppCode.ERROR);
        }
    }

    /**
     * 生成报告
     *
     * @param code
     * @param files
     * @return
     */
    @RequestMapping(value = "/saveReport")
    @ResponseBody
    public ApiResult saveReport(String code, String files) {

        try {
            chainReportService.generateReport(code, files);
            return ApiResult.resultWith(AppCode.SUCCESS);
        } catch (Exception e) {
            return ApiResult.resultWith(AppCode.ERROR);
        }
    }


    /**
     * 报告列表
     *
     * @param code
     * @param model
     * @return
     */
    @RequestMapping("/reportList/{code}")
    public String reportList(@PathVariable("code") String code, Model model) {
        model.addAttribute("code", code);
        model.addAttribute("list", chainReportService.getReportList(code));
        model.addAttribute("test", userGeneTestingRepository.findOne(code));

        return "user/reportslist";
    }


    @RequestMapping("/viewReport")
    public String viewReport(String reportCode, String reportVersion, String barCode, Model model) {
        ReportView reportView = chainReportService.viewReport(reportCode, reportVersion, barCode);
        model.addAttribute("report", reportView);
        return "example/" + reportView.getTemplate();
    }

    @RequestMapping("/downloadReport")
    public void downloadReport(String reportCode, String reportVersion, String barCode, HttpServletResponse response) throws IOException, InterruptedException {

        UserGeneTesting userGeneTesting = userGeneTestingRepository.findOne(barCode);
        List<Report> reports = reportRepository.findReport(reportCode, reportVersion);


        String url = "/user/viewReport?reportCode=" + reportCode + "&reportVersion=" + reportVersion + "&barCode=" + barCode;
        String pdfPath = configService.getReportFileFolder() + "/" + Constant.PDF + "/" + UUID.randomUUID().toString() + ".pdf";
        String wkHtmlToPdf = configService.getWkHtmlToPdfFolder() + "wkhtmltopdf";
        String cmd = wkHtmlToPdf + " --disable-smart-shrinking " + configService.webUrl() + url + " " + pdfPath;
        Process process = Runtime.getRuntime().exec(cmd);
        int exitVal = process.waitFor();
        if (exitVal >= 0) {
            File file = new File(pdfPath);
            if (file.exists()) {
//        String fileName = file.getName();
                DateTimeFormatter simpleDateFormat = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
                String date = simpleDateFormat.format(LocalDateTime.now());
                String fileName = URLEncoder.encode(barCode
                        + (userGeneTesting != null ? userGeneTesting.getUserName() : "")
                        + date
                        + (reports != null && reports.size() > 0 ? reports.get(0).getName() : ""), "UTF-8");
                BufferedInputStream bis;
                OutputStream os = null;
                response.reset();
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
                try {
                    bis = new BufferedInputStream(new FileInputStream(file));
                    byte[] b = new byte[bis.available() + 1000];
                    int i = 0;
                    os = response.getOutputStream();   //直接下载导出
                    while ((i = bis.read(b)) != -1) {
                        os.write(b, 0, i);
                    }
                    os.flush();
                    os.close();
                } catch (IOException e) {
                } finally {
                    if (os != null) {
                        os.close();
                    }
                }
            }
        }
    }

    /**
     * 上链
     *
     * @param code
     * @param model
     * @return
     */
    @RequestMapping("/uploadChain/{code}")
    public String uploadChain(@PathVariable("code") String code, Model model) {
        model.addAttribute("code", code);
        return "user/uploadchain";
    }


    @RequestMapping(value = "/findChainFiles")
    @ResponseBody
    public ApiResult findChainFiles(String code) {

        try {
            return ApiResult.resultWith(AppCode.SUCCESS, chainReportService.findFiles(configService.getReportFileFolder() + "/" + Constant.CHAIN, code));
        } catch (Exception e) {
            return ApiResult.resultWith(AppCode.ERROR);
        }
    }

    /**
     * 上链
     *
     * @param code
     * @param files
     * @param keywords
     * @param mobile
     * @param GCode
     * @param MCode
     * @return
     */
    @RequestMapping(value = "/saveChain")
    @ResponseBody
    public ApiResult saveChain(String code, String files, String keywords, String mobile, String GCode, String
            MCode) {

        try {
            chainReportService.uploadChain(code, files, keywords, mobile, GCode, MCode);
            return ApiResult.resultWith(AppCode.SUCCESS);
        } catch (Exception e) {
            return ApiResult.resultWith(AppCode.ERROR);
        }
    }
}
